define(function (require) {
    require('common/fileuploader');
    var Base = require('group/common/main');
    var utils = require('common/utils/home');
    require('validate');
    var Mask = require('common/mask');
    var mask = new Mask();
    var utils_common = require('common/utils');


    //idname 倒计时id名称， count倒计时秒数，url跳转地址
    function jump(count, url) {
        window.setTimeout(function () {
            count--;
            if (count > 0) {
                $('#jumpTo').html(count);
                jump(count, url);
            } else {
                location.href = url;
            }
        }, 1000);
    }

    return Base.extend({
        initialize: function (params) {
            var _this = this;
            Base.prototype.initialize.apply(this, [params]);
            if (_this['page_' + _global.a]) {
                _this['page_' + _global.a]();
            }
        },
		submit_reload: function (url) {
            var _this = this;
            _this.$('form').validate({
                submitHandler: function (form) {
                    var params = _this.$('form').serializeJson();
                    utils.ajaxPost(params, function (resp) {
                        mask.success(resp.msg, function () {
                            if (url) {
                                window.location.href = url;
                            }
                            else {
                                window.location.reload();
                            }

                        });
                    });
                }
            });
        },
        page_add_user: function () {
            var _this = this;
            $('.J_form').validate({
                submitHandler: function (form) {
                    var params = $('.J_form').serializeJson();
                    utils.ajaxPost(_.extend(params, {g: 'team', m: 'user', a: _global.a}), function (resp) {
                        mask.success(resp.msg);
                        if (resp.url) {
                            _this.redirect(resp.url, 1);
                        } else {
                            _this.redirect(_.U({m: 'user', a: 'team'}), 1);
                        }
                    }, function (resp) {
                        mask.error(resp.msg);
                    });
                }
            });

			$('#tgroup').change(function(){
				var tgroup = $(this).val();
				if(tgroup == ''){
					$('#higherUp').hide();
				}else{
					$.ajax({
						url:_.U({a:'get_tgroup_data'}),
						type:'POST',
						data:{select_tgroup:tgroup},
						dataType:'JSON',
						success:function(result){
							$('#higherUp').show().find('.content').html(result.data);
							_this.select_child();
						}
					});
				}
			});
        },
		select_child:function(){
            var _this = this;
			_this.cate_select({select: 'js-tgroup-select',top_option:'请选择总经销商'});

		},
		cate_select: function (options) {
            var settings = {
                field: 'J_cate_id',
                top_option: "请选择",
                select: 'J_cate_select'
            };
            if (options) {
                $.extend(settings, options);
            }
            var self = $("." + settings.select),
                pid = self.attr('data-pid'),
                uri = self.attr('data-uri'),
                name = self.attr('data-name'),
                nums = self.attr('data-nums'),
                selected = self.attr('data-selected'),
                grade = self.attr('data-grade'),
                selected_arr = [];

            var cate_sel = self.selector;
            if (selected != undefined && selected != '0') {
                if (selected.indexOf('|')) {
                    selected_arr = selected.split('|');
                }
                else {
                    selected_arr = [selected];
                }
            }
            self.nextAll(cate_sel).remove();
            $('<option value="">--' + settings.top_option + '--</option>').appendTo(self);
			var j = 1;

            $.getJSON(uri, {id: pid, grade: grade}, function (result) {
				var list = result.data.list;
                if (list) {
                    for (var i = 0; i < list.length; i++) {
                        $('<option value="' + list[i].id + '">' + list[i].name + '</option>').appendTo(self);
                    }
                }
				bindChange();
                if (selected_arr.length > 0) {
                    //IE6 BUG
                    setTimeout(function () {
                        self.find('option[value="' + selected_arr[0] + '"]').attr("selected", true);
                        self.trigger('change');
                    }, 1);
                }
            });

           
			function bindChange(){
				$("." + settings.select).unbind('change').bind('change', function () {
					if($(this).index() + 1 >= parseInt(nums)){
						return;
					}
					addChild($(this));
				});
			}

			function addChild(_this){
                var _pid = _this.val();
                _this.nextAll(cate_sel).remove();
                if (_pid != '') {
                    $.getJSON(uri, {id: _pid, grade: grade}, function (result) {
                        if (result == null) {
                            return;
                        }
						if(result.status == 0){
							mask.error(result.msg);
                            return;
						}
						var list = result.data.list;
                        if (list) {
                            if (list[0].type == 1 || list[0].type == undefined) {
								if(result.data.top_option != undefined){
									var top_option = result.data.top_option;
								}else{
									var top_option = settings.top_option;
								}
                                var _childs = $('<select class="' + cate_sel.substr(1) + ' mr10" data-pid="' + _pid + '" name="'+name+($('.'+cate_sel.substr(1)).length+1)+'"><option value="">--' + top_option + '--</option></select>')
                                for (var i = 0; i < list.length; i++) {
                                    $('<option value="' + list[i].id + '">' + list[i].name + '</option>').appendTo(_childs);
                                }
                                _childs.insertAfter(_this);
								bindChange();
                                if (selected_arr[j] != undefined) {
                                    //IE6 BUG
                                    //setTimeout(function(){
                                    _childs.find('option[value="' + selected_arr[j] + '"]').attr("selected", true);
                                    _childs.trigger('change');
                                    //}, 1);
                                }
                            }
                            else if (list[0].type == 2) {
                                var _childs = $('<div class="list"><div class="name">' + list[0].name + ': </div><input type="hidden" name="data_id" value="' + list[0].id + '" /><input type="text" class="text" name="data" /></div>');
                                _childs.insertAfter(_this.parents('.list'));
                            }
                            j++;
                        }
                    });
                    $('#' + settings.field).val(_pid);
                }
                else {
                    $('#' + settings.field).val(_this.attr('data-pid'));
                }
			}
        },
		page_profile: function () {
            var _this = this;
            _this.initUpload({
                queueSizeLimit: 1,
                removeCompleted: true,
                onUpload: function () {
                    _this.$('.uploadifive-queue').show();
                },
                _onUploadComplete: function (file, data) {
                    _this.$('.uploadifive-queue').hide();
                    _this.$('.upload_avatar .avatar').attr('src', data.data.fullPath);
                    _this.$('#J_img_hidden').val(data.data.savePath);
                }
            });
            _this.submit_reload();
        },
		page_password: function () {
            var _this = this;
            _this.bind_submit();
        },
		page_pers: function () {
            $('.J_edit_per').click(function(){
				var id = $(this).data('id');
				var pers = $(this).data('pers');
				layer.open({
					id: 'bindtele_layuipro', //设定一个id，防止重复弹出
					title: '设置收益比例',
					shade: 0,
					content: '<form action="'+_.U({m:'user',a:'set_pers'})+'" id="userpersForm">\
							<div class="container">\
								<div class="row">\
									<div class="col-xs-12">收益比例：<input type="text" name="pers" style="width:50px;border: 1px solid #e0e0e0;height:34px;line-height:34px;" value="'+pers+'"> %</div>\
								</div>\
								<div class="row">\
									<div class="col-xs-12 bindtele_error_msg" style="text-align:left;color:red;font-size:12px;"></div>\
								</div>\
							</div>\
							<input type="hidden" name="m" value="user">\
							<input type="hidden" name="a" value="set_pers">\
							<input type="hidden" name="id" value="'+id+'">\
						</form>',
					btn: ['确定', '关闭'],
					shade: 0.8,
					yes: function(){
						var params = $('#userpersForm').serializeJson();
						utils.ajaxPost(_.extend(params), function (data) {
							if(data.error == 1){
								$('.bindtele_error_msg').html(data.msg);
							}else{
								layer.msg('设置成功');
                                window.location.reload();
							}
						});
					},
					btn2: function(){
						layer.closeAll();
					},
					zIndex: layer.zIndex,
					success: function(layero){
						layer.setTop(layero); //重点2
					}
				});


			});
        },
    });
});